from QQLoginTool.QQtool import OAuthQQ
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

# 返回QQ登录网址的视图
from rest_framework_jwt.settings import api_settings

from meiduo import settings
from oauth import serializers
from oauth.models import OAuthQQUser
from oauth.utils import generate_save_user_token



class QQAuthURLView(APIView):
    """
       提供QQ登录页面网址
       GET/oauth/qq/statues/?state=xxx
       next:用户QQ登录成功后进入美多商城的哪个网址

    """
    def get(self,request):
        state = request.query_params.get('state')
        if not state:
            state = '/'
        #获取QQ登录页面网址
            # 1.初始化oauthQQ对象
            # oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
            # client_secret=settings.QQ_CLIENT_SECRET,
            #   redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=state)
        # 2.获取QQ登录扫码页面，扫码后得到Authorization Code
        login_url = oauth.get_qq_url()

        return  Response({
            'login_url':login_url
        })

# 获取QQ用户OpenID
"""
请求方式： GET /oauth/qq/users/?code=xxx
必传参数 code
"""





class  QQAuthUserView(GenericAPIView):
    """用户扫码登录的回调处理"""
    # 指定序列化器
    serializer_class =  serializers.QQAuthUserSerializer


    def get(self,request):
        # 提取code请求参数
        code = request.query_params.get('code')
        if not code:
            return Response(
                {'message':'缺少code'},
                # 400INVALID _REQUEST - [POST / PUT / PATCH]：用户发出的请求有错误，服务器没有进行新建或修改数据的操作
                status = status.HTTP_400_BAD_REQUEST
                )
        # 创建工具对象 初始化oauthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            # 使用code向QQ服务器请求access_token
            access_token = oauth.get_access_token(code)
            # 使用access_token向QQ服务器请求openid
            openid = oauth.get_open_id(access_token)
        except Exception:
            return Response(
                {'message':'QQ服务异常'},
                # 503 超载或临时维护
                status = status.HTTP_503_SERVICE_UNAVAILABLE

            )

        # 使用openid查询该QQ用户是否在美多商城中绑定过用户
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果openid没绑定美多商城用户，创建用户并绑定到openid
            # 为了能够在后续的绑定用户操作中前端可以使用openid，在这里将openid签名后响应给前端
            access_token_openid = generate_save_user_token(openid)
            return  Response(
                {'access_token':access_token_openid}
            )
        else:
            # 如果openid已绑定美多商城用户，直接生成JWT token，并返回
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # 获取oauth_user 关联user
            user = oauth_user.user
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            response = Response(
                {
                    'token':token,
                    'user_id':user.id,
                    'username':user.username
                }
            )
            return response


    def post(self,request):
        """openid绑定到用户"""
        # 获取序列化器对象
        serializer = self.get_serializer(data = request.data)
        # 校验
        serializer.is_valid(raise_exception = True)
        user = serializer.save()


        # 生成JWT token，并响应
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        response = Response({
            'token': token,
            'user_id': user.id,
            'username': user.username
        })
        return response
